package com.hw.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Classname: SentinelController
 * @Description: 描述
 * @Date: 2021/12/13
 * @Author: HuWei
 */
@RestController
@RequestMapping("/sentinel")
@Slf4j
public class SentinelController {

    /**
     * sentinel测试A(QPS)
     */
    @GetMapping("/testA")
    public String testA(){
        return "sentinelTest A";
    }

    /**
     * sentinel测试B(线程数)
     */
    @GetMapping("/testB")
    public String testB(){
        try {
            // 模拟线程处理1.2秒
            TimeUnit.MILLISECONDS.sleep(1200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "sentinelTest B";
    }

    /**
     * 预热
     * @return
     */
    @GetMapping("/testC")
    public String testC(){
        return "sentinelTest C";
    }


    /**
     * 排队
     * @return
     */
    @GetMapping("/testD")
    public String testD(){
        log.info("Name"+Thread.currentThread().getName());
        return "sentinelTest D";
    }

    /**
     * RT测试
     */
    @GetMapping("/testE")
    public String testE(){
        try {
            // 模拟线程处理时间为1s
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("降级规则之RT,测试");
        return "sentinelTest E";
    }

    /**
     * 异常比例
     */
    @GetMapping("/testF")
    public String testF(){
        // 模拟程序出现异常
       int res = 10/0;
       return "sentinelTest F";
    }

    /**
     * 热键
     */
    @GetMapping("/testG")
    @SentinelResource(value = "testG",blockHandler = "testGBlock")
    public String testG(@RequestParam(value = "v1",required = false)String v1,
                        @RequestParam(value = "v2",required = false)String v2){
        return "sentinelTest G";
    }

    /**
     * 自定义熔断返回信息(和方法的形参列表要一样,再加上BlockException)
     * @return
     */
    public String testGBlock(String v1,String v2,BlockException blockException){
        return "testG_Block";
    }
}